using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;
using MyApi.Api.Repository;
using MyApi.Api.Entity;
using MyApi.Api.Params;
using System.Linq;
using MyApi.Api.Utils;

namespace MyApi.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private IConfiguration _configuration;
        private IRepository<Users> _usersRepository;
        private TokenParameter _tokenParameter;
        public UsersController(IConfiguration configuration, IRepository<Users> usersRepository)
        {
            _configuration = configuration;
            _usersRepository = usersRepository;
            _tokenParameter =
               _configuration
                   .GetSection("TokenParameter")
                   .Get<TokenParameter>();
        }
        [HttpGet]
        public dynamic Get([FromQuery] Pager pager)
        {
            var PagerIndex = pager.PagerIndex;
            var PagerSize = pager.PagerSize;
            var users = _usersRepository.Table;
            var u = users.Skip((PagerIndex - 1) * PagerSize).Take(PagerSize).ToList();
            var res = new
            {
                Code = 1000,
                Data = new { Data = u, Pager = new { PagerIndex, PagerSize, rowsTotal = users.Count() } },
                Msg = "获取成功"
            };
            return JsonHelper.Serialize(res);
        }

        [HttpGet("{id}")]
        public dynamic Get(int id)
        {
            var user = _usersRepository.GetById(id);
            return new
            {
                Code = 1001,
                Data = user,
                Msg = "获取成功"
            };
        }

        [AllowAnonymous]
        [HttpPost]
        public dynamic Post(CreateUser newUser)
        {
            var username = newUser.Username.Trim();
            var password = newUser.Password == null ? "123456" : newUser.Password.Trim();
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "账号密码不能为空"
                };
            }
            var user = new Users
            {
                Username = newUser.Username,
                Password = newUser.Password,
                Remarks = newUser.Remarks
            };
            _usersRepository.Insert(user);
            var res = new
            {
                Code = 1000,
                Data = user,
                Msg = "创建成功"
            };
            return JsonHelper.Serialize(res);
        }

        [HttpPut("{id}")]
        public dynamic Put(int id, CreateUser updateUser)
        {
            var username = updateUser.Username;
            var password = updateUser.Password;
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return JsonHelper.Serialize(new
                {
                    Code = 104,
                    Data = "",
                    Msg = "账号或密码不能为空"
                });

            }
            var user = _usersRepository.GetById(id);
            if (user == null)
            {
                return JsonHelper.Serialize(new
                {
                    Code = 104,
                    Data = "",
                    Msg = "用户不存在"
                });
            }
            user.Username = updateUser.Username;
            user.Password = updateUser.Password;
            user.Remarks = updateUser.Remarks;
            _usersRepository.Update(user);
            return JsonHelper.Serialize(new
            {
                Code = 100,
                Data = user,
                Msg = "更新成功"
            });
        }

        [HttpDelete("{id}")]
        public dynamic Delete(int id)
        {
            _usersRepository.Delete(id);
            return new
            {
                Code = 100,
                Data = "",
                Msg = "删除成功"
            };
        }

        [AllowAnonymous]
        [HttpPost, Route("token")]
        public dynamic GetToken(CreateUser newUser)
        {
            var username = newUser.Username.Trim();
            var password = newUser.Password.Trim();

            var user =
                _usersRepository
                    .Table
                    .Where(x =>
                        x.Username == username && x.Password == password)
                    .FirstOrDefault();

            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "用户名或密码不正确，请确认后重试"
                };
            }

            var token =
                TokenHelper.GenerateToken(_tokenParameter, user.Username);
            var refreshToken = "541788";

            return new
            {
                Code = 1000,
                Data = new { username = user.Username, Token = token, refreshToken = refreshToken },
                Msg = "登录成功"
            };
        }

        [AllowAnonymous]
        [HttpPost, Route("refreshtoken")]
        public dynamic RefreshToken(RefreshTokenDTO refresh)
        {
            var username = TokenHelper.ValidateToken(_tokenParameter, refresh);

            if (string.IsNullOrEmpty(username))
            {
                return new { Code = 1002, Data = "", Msg = "token验证失败" };
            }

            var token = TokenHelper.GenerateToken(_tokenParameter, username);
            var refreshToken = "541788";

            return new
            {
                Code = 1000,
                Data = new { Token = token, refreshToken = refreshToken },
                Msg = "刷新token成功"
            };
        }

    }
}